package com.bancomer.batch.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.ValidationResult;

public class FilesWriter {
	public static void writePropertiesFile(FileHelper file, Map<String,String> loads) throws Exception{
        FileWriter properties = new FileWriter(file.getLocalPath()+file.getName(),true);
        PrintWriter pw = new PrintWriter(properties);
        Iterator it = loads.entrySet().iterator();
        while (it.hasNext()) {
    			Map.Entry pairs = (Map.Entry)it.next();
                pw.println(pairs.getKey()+"="+pairs.getValue());
    	}
        properties.close(); 
	}
	public static void writePropertiesFile(FileHelper file, Map<String,String> loads, boolean append) throws Exception{
        FileWriter properties = new FileWriter(file.getLocalPath()+file.getName(),append);
        PrintWriter pw = new PrintWriter(properties);
        Iterator it = loads.entrySet().iterator();
        while (it.hasNext()) {
    			Map.Entry pairs = (Map.Entry)it.next();
                pw.println(pairs.getKey()+"="+pairs.getValue());
    	}
        properties.close(); 
	}
	public static void writeFile(String text,String path,boolean append) throws Exception{
        FileWriter properties = new FileWriter(path,append);
        PrintWriter pw = new PrintWriter(properties);
    	pw.println(text);
        properties.close(); 
	}
	public static void formatXMLFile(String file) throws Exception{
	    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    DocumentBuilder builder = factory.newDocumentBuilder();
	    Document document = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(
	        file))));
	    document.setXmlStandalone(true);
	    Transformer xformer = TransformerFactory.newInstance().newTransformer();
	    xformer.setOutputProperty(OutputKeys.METHOD, "xml");
	    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
	    Source source = new DOMSource(document);
	    Result result = new StreamResult(new File(file));
	    xformer.transform(source, result);
	}
}
